import asyncio
import aioredis
import threading
import time
from setting.redis_setting import *

# 单例模式
class ConnRedis():

    _instance = None
    _initialized = False

    def __new__(cls, *args, **kwargs):#去内存申请地址

        if not cls._instance:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self, loop=None):#可以传入一个指定的永久loop,

        if not self._initialized:
            #创建一个新的事件循环线程
            if loop == None:
                self.newlp = asyncio.new_event_loop()
                
                t = threading.Thread(target=self.thread_running_loop,args=(self.newlp,))     
                t.start()
                
            else:  
                self.newlp = loop

            asyncio.run_coroutine_threadsafe(self.creat_con_pool(),self.newlp)
            print("正在建立mysql线程池")
            time.sleep(1)
            self._initialized = True

    def thread_running_loop(self,loop):#开启loop

        '''
        set_event_loop(eventloop对象)将eventloop对象指定为当前线程的eventloop(非主线程的事件循环)
        '''
        asyncio.set_event_loop(loop)    #在此线程中设置一个新的事件循环,默认情况下事件循环是主线程的
        loop.run_forever()


    async def creat_con_pool(self):
        '''
        使用create_pool创建一个连接池
        '''

        self.pool_=await aioredis.create_redis_pool(REDIS_HOST, 
                                                    password=REDIS_PASSWORD,
                                                    loop=self.newlp,
                                                    encoding="utf8"
                                                
                                                    )
        print("mysql线程池开启完毕~~~")

        













